import ValidationException from "../exception/validation.ex";
import { plainToInstance } from "class-transformer";
import { validate, ValidationError } from "class-validator";
import * as express from "express";
/**
 *
 * @param dto
 * @param skipMissingProperties 默认为false,如果需要验证 patch类的dto，传入true
 * @returns
 */
function validationMiddleware<T>(
  dto: any,
  skipMissingProperties = false
): express.RequestHandler {
  return (req, res, next) => {
    validate(plainToInstance(dto, req.body), { skipMissingProperties }).then(
      (errs: ValidationError[]) => {
        if (errs.length > 0) {
          const messages = errs
            .map((err) => {
              return Object.values(err.constraints);
            })
            .join(",");
          
            
          next(new ValidationException(messages));
        } else {
          next();
        }
      }
    );
  };
}

export default validationMiddleware;
